<template>
	<el-dialog v-model="visible" append-to-body width="1000" fullscreen destroy-on-close :close-on-click-modal="false" @closed="$emit('closed')">
		<el-main class="page">
			<el-header style="padding: 0px">
				<div class="left-panel">
					<el-page-header :content="titleMap[mode]" @back="$emit('closed')"/>
				</div>
				<div class="right-panel">
					<div v-if="mode=='edit'">表名：{{ form.tableName }}</div>
					<!--el-button type="primary" icon="el-icon-finished" :loading="isSaveing" @click="createModel()" :disabled="active < 1">保 存</el-button-->
				</div>
			</el-header>
			<el-steps :active="active" finish-status="process" simple class="steps" style="width: 800px;margin: 35px auto;background: #FFF;">
				<el-step title="基础信息"/>
				<el-step title="字段配置"/>
				<el-step title="创建成功"/>
			</el-steps>
			<el-form :model="form" :rules="rules" :disabled="mode=='show'" ref="dialogForm" label-width="100px" size="large">
			   <el-row v-if="active==0">
				<el-col :span="24">
						<el-form-item label="表名(中文)" prop="tableComment">
							<el-input v-model="form.tableComment" @blur="getPinYin" :disabled="mode == 'edit'" maxlength="30" placeholder="数据表的中文名称" >
								<template #append>
									<el-button icon="el-icon-search" @click="getPinYin">生成表名</el-button>
								</template>
							</el-input>
						</el-form-item>
						<el-row>
							<el-col :span="14">
								<el-form-item label="表名(英文)" prop="tableName">
									<template #label>
										<div style="margin-top:2px">表名(英文)</div>
									</template>
									<el-input placeholder="数据表的英文名称" :disabled="mode == 'edit'" v-model="form.tableName" maxlength="50" suffix-icon="el-icon-scale-to-original">
										<template #prepend>{{tablePrefix}}</template>
									</el-input>
									<el-alert description="默认由系统自动生成拼音表名，如需修改请自行输入" type="warning" :closable="false" style="padding: 0px"/>
								</el-form-item>
							</el-col>
							<el-col :span="10">
								<el-form-item label="数据存储" prop="connectId">
									<jd-select v-model="form.connectId" :disabled="mode == 'edit'" :apiObj="$API.app.dbConn.getConnects" :apiProps="{label:'connName',value: 'connId'}" style="width: 100%;" placeholder="请选择..."></jd-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-form-item label="表的说明" prop="tableExplain">
							<el-input v-model="form.tableExplain" maxlength="500" :disabled="mode == 'edit'" type="textarea" rows="5" show-word-limit placeholder="该数据表的说明文字，方便后期管理维护" />
						</el-form-item>
				</el-col>
			</el-row>
			<el-row v-if="active==1">
				<el-col :span="24">
					<jd-form-table v-model="form.list" :addTemplate="addTemplate"  drag-sort placeholder="暂无数据">
						<el-table-column prop="field" label="字段名称">
							<template #default="scope">
								<el-input v-model="scope.row.field" :disabled="check(scope.row.field)"  placeholder="Field值，仅限输入英文"></el-input>
							</template>
						</el-table-column>
						<el-table-column prop="val" label="字段说明">
							<template #default="scope">
								<el-input v-model="scope.row.comment" :disabled="check(scope.row.field)" placeholder="Comment值，请输入中文名称"></el-input>
							</template>
						</el-table-column>
						<el-table-column prop="dataType" label="字段类型" width="150" align="center">
							<template #default="scope">
								<el-select v-model="scope.row.type" placeholder="请选择类型..." :disabled="check(scope.row.field)" style="width: 100%;" @change="changeType($event,scope.row)">
									<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
								</el-select>
							</template>
						</el-table-column>
						<el-table-column prop="length" label="字段长度" width="150" align="center" style="text-align: center;">
							<template #default="scope">
								<el-input v-model="scope.row.length" :disabled="check(scope.row.field)" placeholder="请输入长度"></el-input>
							</template>
						</el-table-column>
						<!--el-table-column prop="primaryKey" label="主键" align="center" width="100">
							<template #default="scope">
								<el-checkbox v-model="scope.row.primaryKey" :disabled="check(scope.row.field)" @change='changeKey($event,scope.row)'
                :true-label="1" :false-label="0" />
							</template>
						</el-table-column-->
						<el-table-column prop="allowNull" label="允许空" align="center" width="150">
							<template #default="scope">
								<el-checkbox v-model="scope.row.allowNull" :disabled="check(scope.row.field)" @change='changeAllowNull($event,scope.row)'
                :true-label="1" :false-label="0" />
							</template>
						</el-table-column>
					</jd-form-table>
				</el-col>
			   </el-row>
			</el-form>
			<el-row v-if="active==2" style="justify-content: center">
				<el-result
					icon="success"
					title="恭喜，模型创建成功"
					sub-title="下面请到应用中心，创建一个专属的表单模型吧。"
				>
					<template #extra>
						<el-button @click="$emit('closed')">返回列表</el-button>
						<el-button type="primary" @click="designApp">应用中心</el-button>
					</template>
				</el-result>
			</el-row>
			<el-row style="margin-top: 35px; justify-content: right;">
				<el-button :disabled="active <= 0" @click="handlePrevStep" v-if="active == 1 && mode=='add'"><i class="jd-icon icon-prev" style="margin-right: 5px;"></i>上一步</el-button>
				<el-button type="primary" :disabled="active >= 1" @click="handleNextStep" v-if="active <= 0 && mode=='add'">下一步<i class="jd-icon icon-next" style="margin-left: 5px;"></i></el-button>
				<el-button type="primary" :loading="btnLoading" :disabled="active < 1" @click="createModel()" v-if="active == 1"><i class="jd-icon icon-save" style="margin-right: 5px;"></i>保 存</el-button>
			</el-row>
		</el-main>
	</el-dialog>
</template>

<script>
	export default {
		emits: ['success', 'closed'],
		props: {
			interfaceId: { type: Number, default: 0 },
			group:null,
		},
		data() {
			return {
				mode: "add",
				titleMap: {
					add: '创建模型',
					edit: '编辑模型',
					show: '查看'
				},
				array:['id','del_flag','create_by','create_time','update_by','update_time','remark'],
				// 表名前缀
				tablePrefix:"app_",
				// 提交按钮加载
				btnLoading:false,
				visible: false,
				active: 0,
				addTemplate: {
					field: '',
					type: 'varchar',
					length: 50,
					primaryKey: 0,
					allowNull: 1
				},
				primaryField:[
					{field:"id",type:"varchar",length:"64","primaryKey":true,"allowNull":false,"comment":"ID"}
				],
				tableField:[
					{field:"del_flag",type:"char",length:"2","primaryKey":false,"allowNull":true,"comment":"逻辑删除"},
					{field:"create_by",type:"varchar",length:"64","primaryKey":false,"allowNull":true,"comment":"创建者"},
					{field:"create_time",type:"datetime",length:"0","primaryKey":false,"allowNull":true,"comment":"创建时间"},
					{field:"update_by",type:"varchar",length:"64","primaryKey":false,"allowNull":true,"comment":"更新者"},
					{field:"update_time",type:"datetime",length:"0","primaryKey":false,"allowNull":true,"comment":"更新时间"},
					{field:"remark",type:"varchar",length:"500","primaryKey":false,"allowNull":true,"comment":"逻辑删除"}
				],
				//表单数据
				form: {
					id:null,
					appId:null,
					modelType:'model',
					list:[]
				},
				//验证规则
				rules: {
					tableName:[
						{required: true, message: '请输入表名称'}
					],
					tableComment:[
						{required: true, message: '请输入中文表名'}
					],
					connectId:[
						{required: true, message: '请选择数据库'}
					],
				},
				options: [
					{ label: '字符串', value: 'varchar' },
					{ label: '整型', value: 'int' },
					{ label: '日期时间', value: 'datetime' },
					{ label: '浮点', value: 'decimal' },
					{ label: '长整型', value: 'bigint' },
					{ label: '文本', value: 'longtext' }
				]
			}
		},
		mounted() {
			let appId = this.$route.query.appId;
			if (typeof(appId) != 'undefined'){
				this.form.appId = appId;
			}
		},
		methods: {
			//显示
			open(mode='add'){
				this.mode = mode;
				this.visible = true;
				this.requestParams = [];
				return this
			},
			// 获取应用拼音
			async getPinYin(){
				var res = await this.$API.app.appStore.getFirstPhonetic.get(this.form.tableComment)
				console.log(res)
				if (res.code == 200){
					// TODO 根据appId获取app详情-现在是固定的
					let app = await this.$API.app.appStore.getInfo.get(this.form.appId);
					if (app.code == 200){
						this.form.tableName = app.data.appPackage+"_"+res.data;
					}

				}
			},
			// 类型改变
			changeType(val, row){
				if (row.primaryKey == 1){
					this.$alert("主键类型不能修改", "提示", {type: 'error'})
					row.type ='int';
					return
				}
			},
			check(val){
				return this.array.find((item)=>{
					return item==val;
				})
			},
			handlePrevStep(){
				this.active -= 1;
      			this.$refs.dialogForm.clearValidate();
			},
			handleNextStep(){
				this.$refs.dialogForm.validate((valid) => {
					if (valid) {
						if (this.active < 1){
							this.active += 1;
						}
					}
				});
			},
			// 设置主键
			changeKey(val, row) {
				// 如果设置为主键
			    if (val == 1){
					row.allowNull = 0;
					row.type ='int';
				  for (let i = 0; i < this.form.list.length; i++) {
					  if (this.form.list[i] != row){
						  this.form.list[i].primaryKey = 0;
					  }
				  }
				}

			},
			// 校验是否存在
			exist() {
				let isOk = true;
				//  遍历数组，判断非空
				for (let i = 0; i < this.form.list.length; i++) {
					const e = this.form.list[i];
					if (!e.field) {
						this.$message({
							showClose: true,
							message: `第${i + 1}行列名不能为空`,
							type: 'error',
							duration: 1000
						});
						isOk = false
						break
					}
					let reg = /(^_([a-zA-Z0-9]_?)*$)|(^[a-zA-Z](_?[a-zA-Z0-9])*_?$)/
					if (!reg.test(e.field)) {
						this.$message({
							showClose: true,
							message: `第${i + 1}行列名格式错误，请重新输入`,
							type: 'error',
							duration: 1000
						});
						isOk = false
						break
					}
					let num = this.form.list.filter(o => o.field == e.field)
					if (num.length > 1) {
						this.$message({
							showClose: true,
							message: `第${i + 1}行列名'${e.field}'已重复`,
							type: 'error',
							duration: 1000
						});
						isOk = false
						break
					}
					if (!e.comment) {
						this.$message({
							showClose: true,
							message: `第${i + 1}行说明不能为空`,
							type: 'error',
							duration: 1000
						});
						isOk = false
						break
					}
				}
				return isOk;
			},
			// 设置允许空
			changeAllowNull(val,row){
				if (row.primaryKey == 1){
					this.$alert("主键不能为空", "提示", {type: 'error'})
					row.allowNull = 0;
					return
				}
			},
			// 创建模型
			createModel(){
				if (this.form.list.length == 0){
					this.$message({
						showClose: true,
						message: `字段列表不能为空`,
						type: 'error',
						duration: 1000
					});
					return;
				}
				this.$refs.dialogForm.validate(async (valid) => {
					if (valid && this.exist()) {
						this.btnLoading = true;
						this.form.tableFields = JSON.stringify(this.form.list);
						// 加入默认字段
						var modelFields = [...this.primaryField,...this.form.list, ...this.tableField];
						this.form.modelFields = JSON.stringify(modelFields);

						var res = {};
						if (this.form.id == null){
							// 新增
							this.form.tableName = this.tablePrefix + this.form.tableName;
							res = await this.$API.app.model.saveDataModel.post(this.form);
						}else {
							// 修改
							res = await this.$API.app.model.update.put(this.form);
						}
						if(res.code == 200){
							this.$emit('success', this.form, this.mode)
							this.active = 2;
						}else {
							this.$alert(res.msg, "提示", {type: 'error'})
							this.form.tableName="";
						}
						this.btnLoading=false;
					}
				})
			},
			// 应用中心
			designApp(){
				this.$router.push('/app/store');
			},
			setData(data){
				this.active = 1;
				Object.assign(this.form, data);
				var fields = JSON.parse(data.tableFields);
				// 去除主键
				fields = fields.filter(item1 => !this.primaryField.some(item2 => item2.field.toLowerCase() === item1.field.toLowerCase()));
				// 去除默认字段
				fields = fields.filter(item1 => !this.tableField.some(item2 => item2.field.toLowerCase() === item1.field.toLowerCase()));
				//this.form.list=JSON.parse(data.tableFields);
				this.form.list = fields;
			}
		}
	}
</script>
<style>
.el-dialog__body{
	padding: 20px;
	padding-right: 30px;
}
.steps{
	margin-bottom: 30px;
}
</style>
